package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.constant.RedisConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加菜品
     * @param dishDTO
     * @return
     */
    @Override
    @Transactional
    public void addDish(DishDTO dishDTO) {
        // 构建菜品对象
        Dish dish = Dish.builder()
                        .status(StatusConstant.ENABLE)
                        .build();
        // 同名属性赋值
        BeanUtils.copyProperties(dishDTO, dish);
        // 添加菜品
        dishMapper.addDish(dish);

        // 判断是否有菜品口味对象
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && flavors.size() != 0){
            for (int i = 0; i < flavors.size(); i++) {
                                        // 主键回显
                flavors.get(i).setDishId(dish.getId());
            }
            dishFlavorMapper.addDishFlavor(flavors);
        }
        clearCache(RedisConstant.DISH_KEY + dish.getCategoryId());
    }

    /**
     * 分页查询菜品
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        int page = dishPageQueryDTO.getPage();
        int pageSize = dishPageQueryDTO.getPageSize();

        PageHelper.startPage(page, pageSize);
        List<DishVO> dishVOList = dishMapper.page(dishPageQueryDTO);
        PageInfo<DishVO> dishVOPageInfo = new PageInfo<>(dishVOList);

        long total = dishVOPageInfo.getTotal();
        List<DishVO> list = dishVOPageInfo.getList();

        PageResult pageResult = new PageResult();
        pageResult.setTotal(total);
        pageResult.setRecords(list);

        return pageResult;
    }

    /**
     * 启售/停售菜品
     * @param status
     * @param id
     */
    @Override
    public void enableOrDisable(Integer status, Long id) {

        Dish dish = Dish.builder()
                        .status(status)
                        .id(id)
                        .build();

        dishMapper.update(dish);
        clearCache(RedisConstant.DISH_KEY + "*");
    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        DishVO dishVO = dishMapper.getById(id);
        List<DishFlavor> flavors = dishFlavorMapper.getFlavorById(id);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Transactional
    @Override
    public void deleteBatch(List<Long> ids) {

        // 判断当前菜品是否能够删除---是否存在启售中的菜品
        for (int i = 0; i < ids.size(); i++) {
            Integer dishMapperEnable = dishMapper.isEnable(ids.get(i));
            if(dishMapperEnable == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        // 判断当前菜品是否能够删除---菜品是否被包含在套餐中
        List<SetmealDish> setmealDishes = setmealDishMapper.getByIds(ids);
        if(setmealDishes.size() > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        // 根据菜品id批量删除菜品数据
        dishMapper.deleteBatch(ids);
        // 根据菜品id批量删除关联的口味数据
        dishFlavorMapper.deleteBatch(ids);
        clearCache(RedisConstant.DISH_KEY + "*");
    }

    /**
     * 更新菜品信息
     * @param dishDTO
     */
    @Transactional
    @Override
    public void update(DishDTO dishDTO) {
        Dish dish = Dish.builder().build();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);

        List<Long> arr = new ArrayList<>();
        arr.add(dish.getId());
        dishFlavorMapper.deleteBatch(arr);

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && flavors.size() != 0){
            for (int i = 0; i < flavors.size(); i++) {
                // 主键回显
                flavors.get(i).setDishId(dish.getId());
            }
            dishFlavorMapper.addDishFlavor(flavors);
        }
        clearCache(RedisConstant.DISH_KEY + "*");
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    //TODO 1.使用多表联合查询进行优化
    //TODO 2.缓存穿透问题
    @Override
    public List<DishVO> getByCategoryId(Long categoryId) {

        // 构造redis中的key
        String key = RedisConstant.DISH_KEY + categoryId;

        // 查询redis中是否存在菜品数据
//        List<DishVO> dishes = (List<DishVO>) JSON.parse((String) redisTemplate.opsForValue().get(key));
        List<DishVO> dishes = (List<DishVO>) redisTemplate.opsForValue().get(key);
        // 如果存在，直接返回
        if(dishes != null && dishes.size() > 0){
            return dishes;
        }

        // 如果不存在，查询数据库，将查询到的数据放到redis中
        dishes = dishMapper.getByCategoryId(categoryId);
        for (DishVO dish : dishes) {
            List<DishFlavor> flavors = dishFlavorMapper.getFlavorById(dish.getId());
            dish.setFlavors(flavors);
        }

        String json = JSON.toJSONString(dishes);
        redisTemplate.opsForValue().set(key, dishes, RedisConstant.DISH_TTL, TimeUnit.MINUTES);
        return dishes;
    }


    //TODO 优化删除缓存的方式
    public void clearCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
